const log = require('../../utils/log');
const modeTz = require('./modeTz');
const gameCom = require("../gameCommon/gameCommon");
const redisBase = require('../../common/RedisBase');
const CmdTz = require('../proto/CmdTz');
const {Respones,RewardType} = require("../../config/gameCfg");

//每日挑战
class GameTz {
    static getInstance(){
        if(!GameTz.instance){
            GameTz.instance = new GameTz();
            return GameTz.instance;
        }else{
            return GameTz.instance;
        }
    }
    constructor() {
        this.costTime = 10; //答题消耗的时间
    }

    //重置asCurNum ，用于记录当前组答对了多少道题目
    async initInfoList(uid){
        let list = await redisBase.getGameTzInfoList();
        for (let i = 0; i < list.length; i++) {
            let cfg = JSON.parse(list[i]);
            if(cfg.uid === uid){
                cfg.asCurNum = 0;
                await redisBase.updateGameTzInfoList(i,JSON.stringify(cfg));
                break;
            }
        }
    }

    //场景
    async on_game_scene(data,ctype,client){
        log.warn("====on_game_scene==========",data);
        let uid = data.userId;

        //重置asCurNum
        await this.initInfoList(uid);

        let ret = {
            type: ctype,
            data:{
                //题目数组
                topics:[],
                //奖励的内容数据数组
                listReward:[],
                //当前轮答对数量
                curNum:0
            }
        }

        //step1:取game_tz_info_list 列表数据
        log.info('=====step1:取game_tz_info_list 列表数据======');
        let user=  await modeTz.getUserInfoByUid(uid);
        if(user){
            ret.data.curNum = user.asCurNum;

            //step2：奖励数据
            log.info('=====step2：奖励数据=====');
            let gType = user.gType;
            let res = await modeTz.getRewardList(gType);
            log.info('=====step2：奖励数据=====',res);
            if(res){
                let rds = res.rewards;
                for (let i = 0; i < rds.length; i++) {
                    let tp = rds[i];
                    let temp = {
                        //答对题目数
                        topicNum: tp.topicNum,
                        //奖励类型 RewardType
                        rewardType: tp.rewardType,
                        //奖励数量
                        rewardNum: tp.rewardNum
                    }
                    ret.data.listReward.push(temp);
                }

                //step3:取牌的数据
                log.info('=====step3:取牌的数据======');
                let count = res.total;
                let tids = await modeTz.getTopics(uid,count);
                for (let i = 0; i < tids.length ; i++) {
                    let tmp = {
                        tidx: i,
                        //时间限制
                        time: this.costTime,
                        //题目id
                        topicId: tids[i]
                    }
                    ret.data.topics.push(tmp);
                }

                //step4: 返回
                log.info('=====step4: 返回=====');
                client.send(JSON.stringify(ret));
            }
        }
    }

    //用户答题
    async on_user_answer(data,ctype, client){
        let uid = data.userId;
        let tid = data.tid;
        let cid = data.cid;

        let ret = {
            type: ctype,
            data:{
                code: Respones.OK,
                status: 0, // 1 是答对 2 是答错
                tid: tid,
                cid: cid,
            }
        }

        let list = await redisBase.getGameTzInfoList();
        if(list){
            for (let i = 0; i < list.length; i++) {
                let user = JSON.parse(list[i]);
                let gType = user.gType;
                if(user.uid === uid){
                    let cfg = await redisBase.getGameTzCfgByType(gType);
                    let cur = user.asCurNum;
                    let total  = cfg.total;

                    let topicCfg = gameCom.getItemById(tid);
                    if(topicCfg){
                        if(cid === topicCfg.Answer){ //答对继续
                            user.asCurNum++;
                            ret.data.status = 1;

                            //将答对的题目记录,下次不用再次回答
                            await modeTz.addAsCurTid(uid,tid);

                            //判断当前组是否答完
                            if(user.asCurNum >= total){ //完毕 结算
                                this.noticeGameEnd(client,500,1,gType,user.asCurNum);
                            }else{  //否者 通知下一题
                                this.noteNext(client,500,user.asCurNum,total);
                            }
                            //更新到redis
                            await redisBase.updateGameTzInfoList(i,JSON.stringify(user));
                            // end
                        }else{ //答错结算
                            ret.data.status = 2;
                            try{  //通知正确答案
                                this.noticeCurRes(client,500,topicCfg.Answer,tid);
                            }finally {  //结算
                                this.noticeGameEnd(client,1000,2,gType,user.asCurNum);
                            }
                        }
                    }
                    break;
                }
            }
        }

        client.send(JSON.stringify(ret));
    }

    //用户答题超时
    async on_user_answer_timeout(ctype, data, client){
        let uid = data.userId;
        let tid = data.tid;
        let cid = -1;

        let ret = {
            type: ctype,
            data:{
                cid: 0,
            }
        }

        let list = await redisBase.getGameTzInfoList();
        if(list){
            for (let i = 0; i < list.length; i++) {
                let user = JSON.parse(list[i]);
                let gType = user.gType;
                if(user.uid === uid){
                    let cfg = await redisBase.getGameTzCfgByType(gType);
                    let cur = user.asCurNum;
                    let total  = cfg.total;

                    let topicCfg = gameCom.getItemById(tid);
                    if(topicCfg){  //答错结算
                        ret.data.cid = topicCfg.Answer;
                        try{  //通知正确答案
                            this.noticeCurRes(client,500,topicCfg.Answer,tid);
                        }finally {  //结算
                            this.noticeGameEnd(client,1000,2,gType,user.asCurNum);
                        }
                    }
                }
                break;
            }
        }
        client.send(JSON.stringify(ret));
    }

    //通知下一题
    noteNext(client,time,cur,total){
        log.info('======noteNext========');
        setTimeout(()=>{
            let ret = {
                type: CmdTz.StartAnswerTzNextNotice,
                data:{
                    curNum: cur,
                    totalNum:total
                }
            }
            client.send(JSON.stringify(ret));
        },time);

    }
    //通知正确结果
    noticeCurRes(client, time,_cid,_tid){
        log.info('======noticeCurRes========');
        let ret= {
            type: CmdTz.StartAnswerTzErrNotice,
            data:{
                //当前题目id
                tid: _tid,
                //当前题目的正确答案
                cid: _cid
            }
        }
        setTimeout(()=>{
            client.send(JSON.stringify(ret));
        },time);
    }

    /**
     * 通知结算
     * @param client
     * @param time
     * @param isAll
     * @param gType
     * @param anNum  我答对的题目数
     * @returns {Promise<void>}
     */
    async noticeGameEnd(client, time,isAll,gType,anNum){
        log.info('======noticeGameEnd========');

        let ret = {
            type: CmdTz.StartAnswerTzEndNotice,
            data:{
                //是否全部答对 1 是全部回答正确 2 是中间有答错的
                isAll: isAll,
                //奖励
                reward:{
                    rewardType: 0,
                    // 奖励数量
                    rewardNum: 0,
                }
            }
        }


        let cfg = await redisBase.getGameTzCfgByType(gType);
        let rds = cfg.rewards;
        for (let i = 0; i < rds.length; i++) {
            let tp = rds[i];
            if(anNum >= tp.topicNum){
                ret.data.reward.rewardType = tp.rewardType;
                ret.data.reward.rewardNum += tp.rewardNum;
            }
        }

        setTimeout(()=>{
            client.send(JSON.stringify(ret));
        },time)
    }

    //用户失败复活
    async on_user_fuhuo(data,ctype, client){
        let uid = data.userId;
        let ret = {
            type: ctype,
            data:{
                //成功失败 code = 1, 表示成功
                code: 0,
                //当前复活的题目id
                tid: 0
            }
        }

        let list = await redisBase.getGameTzInfoList()
        for (let i = 0; i < list.length; i++) {
            let cfg = JSON.parse(list[i]);
            if(cfg.uid === uid){
                if(cfg.curFuHuo >= cfg.maxFuhuo){ //复活失败
                    ret.data.code = Respones.TZ_FUOHUO_ERR;
                }else{
                    ret.data.code = Respones.OK;
                    cfg.curFuHuo++;
                    await redisBase.updateGameTzInfoList(i,JSON.stringify(cfg));
                }
                break;
            }
        }

        client.send(JSON.stringify(ret));
    }

    //用户领取结算奖励
    async on_user_getenRed(data,ctype, client){
        let uid = data.userId;
        let bei = data.beiShu;

        let ret = {
            type: ctype,
            data:{
                code:Respones.OK
            }
        }

        //step1:查找奖励数据
        let user = await redisBase.getGametzInfoByUid(uid);
        if(user){
            let gType = user.gType;
            let asCurNum = user.asCurNum;

            let cfg = await redisBase.getGameTzCfgByType(gType);
            let rds = cfg.rewards;
            let rdType = 0;
            let rdNum = 0;
            for (let i = 0; i < rds.length; i++) {
                let tp = rds[i];
                if(asCurNum >= tp.topicNum){
                    rdType = tp.rewardType;
                    rdNum += tp.rewardNum;
                }
            }

            rdNum = bei *rdNum;

            //step2: 修改用户的数据
            let ulist = await redisBase.getUserList();
            for (let i = 0; i < ulist.length; i++) {
                let user = JSON.parse(ulist[i]);
                if(user.userId === uid){
                    if(rdType === RewardType.Type_Quan){
                        user.ticket = user.ticket*1 + rdNum;
                    }else if(rdType === RewardType.TYpe_QiuNum){
                        user.ballNum = user.ballNum*1 + rdNum;
                    }
                    await redisBase.updateUserist(i,JSON.stringify(user));
                    break;
                }
            }

            //step3: 返回
            client.send(JSON.stringify(ret));
        }
    }
}

module.exports = GameTz.getInstance();